//
//  RHDataViewController.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/5.
//

#import "RHDataViewController.h"
#import "DataTopView.h"
#import "RHDeviceUserCell.h"
#import "RHDataTypeCell.h"
#import "RHDataDevStateCell.h"
#import "RHAlarmFaultListVC.h"
#import "RHDeviceViewController.h"
#import "RHMyPlantVC.h"
#import "RHDeviceOnlineModel.h"
#import "RHDeviceTypeModel.h"
#import "RHUserListVC.h"
#import "CDZQRScanViewController.h"
#import "RHNavigationController.h"
#import "RHFaultAlarmDeviceVC.h"
#import "IFMMenu.h"
#import "RHUserBindVC.h"

@interface RHDataViewController ()<UITableViewDataSource,UITableViewDelegate,DeviceUserCellDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *datas;

@property (nonatomic, strong) DataTopView *topview;

@property (nonatomic, strong) NSArray *deviceTypeArr;

@property (nonatomic, strong) NSDictionary *devStatusDic;
@end

@implementation RHDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"数据".rh_localized;
    self.datas = @[@{CellSectionTitle:@"设备类型".rh_localized},
                   @{CellSectionTitle:@"设备&电站".rh_localized,
                     CellTitle:@"电站".rh_localized,
                     CellCount:@"--",
                     CellIcon:@"data_plant",
                     CellTitle_1:@"设备".rh_localized,
                     CellCount_1:@"--",
                     CellIcon_1:@"data_device",
                    CellAction:@[@"goToUserOrPlantList",@"goToDeviceList"]
                 }.mutableCopy,
                   @{CellSectionTitle:@"",
                     CellTitle:@"告警数量".rh_localized,
                     CellCount:@"--",CellIcon:@"data_alarm",
                     CellTitle_1:@"故障数量".rh_localized,
                     CellCount_1:@"--",
                     CellIcon_1:@"data_fault",
                     CellAction:@[@"goToAlarmList",@"goToFaultList"]}.mutableCopy
                ];
    
    [self setupUI];

}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    RHNavigationController *nav = (RHNavigationController*)self.navigationController;
    [nav setBackgoundClear:YES titleColor:kCOLOR_HEX(@"333333")];
    [self getAllData];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    RHNavigationController *nav = (RHNavigationController*)self.navigationController;
    [nav setBackgoundClear:NO titleColor:kCOLOR_HEX(@"333333")];
}


#pragma mark ------ 获取个人信息 --------
-(void)checkAccountInfo
{
   
//    NSString *row3_section;
//    NSString *row3_title1;
//    NSString *row3_icon1;
//    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser||
//       [PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser){
//        row3_section = @"电站&设备".rh_localized;
//        row3_title1 = @"电站".rh_localized;
//        row3_icon1 = @"data_plant";
//    }else{
//        row3_section = @"用户&设备".rh_localized;
//        row3_title1 = @"用户".rh_localized;
//        row3_icon1 = @"data_user";
//    }
//    self.datas[2][CellSectionTitle] = row3_section;
//    self.datas[2][CellTitle] = row3_title1;
//    self.datas[2][CellIcon] = row3_icon1;
//    
//    [self.tableView reloadData];
   
}

-(void)getAllData
{
    [QMUITips showLoadingInView:self.view];
    [self getDeviceOnline];      //在线设备数量
    [self getDeviceProportion];  //设备分布
    [self getPlantAndDevice];    //电站,设备,下级用户
    [self checkAccountInfo];
}

-(void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getAllData) name:SwitchRegionSuccessNotification object:nil];
    //普通用户扫描二维码绑定上级用户
    if([PrivateMange share].currentUser.hierarchyCode >= UserRoleTypeBrandMerchants){
        UIBarButtonItem *scanBtn = [UIBarButtonItem itemWithImage:@"user_bind_icon" ImageHighLight:@"user_bind_icon" Target:self Seletor:@selector(showMenu) CGRect:CGRectMake(0, 0, 30, 30)];
        
        self.navigationItem.rightBarButtonItem = scanBtn;
    }
    
    UIImageView *bgImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"kwt_home_bg"]];
    bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
        make.height.equalTo(bgImageView.mas_width).multipliedBy(724/750.0);
    }];
    
   
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [_tableView registerClass:[RHDeviceUserCell class] forCellReuseIdentifier:@"RHDeviceUserCell"];
    [_tableView registerClass:[RHDataTypeCell class] forCellReuseIdentifier:@"RHDataTypeCell"];
    [_tableView registerClass:[RHDataDevStateCell class] forCellReuseIdentifier:@"RHDataDevStateCell"];
    [_tableView setSeparatorColor:kRGB(240, 240, 240) ];
    _tableView.estimatedRowHeight = 500;
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
    }];
    kWeakSelf;
    [self.tableView addHeaderRefresh:^{
        [weakSelf getAllData];
    }];
}

-(void)showMenu
{
    kWeakSelf;
   NSMutableArray *menuItems = [[NSMutableArray alloc] initWithObjects:
                  
    [IFMMenuItem itemWithImage:[UIImage imageNamed:@"user_bind_enter"]
                         title:@"手动绑定".rh_localized
                        action:^(IFMMenuItem *item) {
          [weakSelf bindToSuper];
      }],
    [IFMMenuItem itemWithImage:[UIImage imageNamed:@"user_bind_scan"]
                         title:@"扫码绑定".rh_localized
                        action:^(IFMMenuItem *item) {
          [weakSelf scanQRC];
     }],nil];
    IFMMenu *menu = [[IFMMenu alloc] initWithItems:menuItems];
    menu.menuCornerRadiu = 8;
    menu.showShadow = YES;
    menu.minMenuItemHeight = 45;
    menu.titleColor = [UIColor colorWithHexString:@"3F4443" alpha:0.6];
    menu.titleFont = [UIFont systemFontOfSize:15];
    menu.menuBackgroundStyle = IFMMenuBackgroundStyleLight;
    [menu showFromNavigationController:self.navigationController WithX:[UIScreen mainScreen].bounds.size.width-32];
}

-(void)bindToSuper
{
    RHUserBindVC *bindVC = [[RHUserBindVC alloc]init];
    [self.navigationController pushViewController:bindVC animated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datas.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0){
        return 0.1;
    }
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section == 0) return [UIView new];
    UIView *sectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 25)];
    QMUILabel *lab = [[QMUILabel alloc]initWithFrame:CGRectMake(20, 0, 200, 25)];
    lab.text = self.datas[section][CellSectionTitle];
    if(section == 2) {
        lab.y = 15;
    }
    [sectionView addSubview:lab];
  
    return nil;
    
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){//设备类型
        RHDataTypeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHDataTypeCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.typeModelArr = self.deviceTypeArr;
        return cell;
    }
    //用户&设备
    if (indexPath.section == 1) {
        RHDeviceUserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHDeviceUserCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(cell==nil)
        {
            cell = [[RHDeviceUserCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RHDeviceUserCell"];
        }
        cell.data = self.datas[indexPath.section];
        cell.delegate = self;
        return cell;
    }
    //设备状态
    if (indexPath.section == 2) {
        RHDataDevStateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHDataDevStateCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dic = self.devStatusDic;
        return cell;
    }
    return [UITableViewCell new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  UITableViewAutomaticDimension;
}
//电站或人员列表
-(void)goToUserOrPlantList
{
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser||[PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser){
        RHMyPlantVC *vc = [[RHMyPlantVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        RHUserListVC *vc = [[RHUserListVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
#pragma mark --------- 设备列表
-(void)goToDeviceList
{
    RHDeviceViewController *vc = [[RHDeviceViewController alloc] init];
    vc.userId = [PrivateMange share].currentUser.userId;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --------- 告警 故障 列表
-(void)goToAlarmList
{
   
    RHFaultAlarmDeviceVC *listVC = [[RHFaultAlarmDeviceVC alloc]init];
    listVC.userId = [PrivateMange share].currentUser.userId;
    listVC.index = 0;
    [self.navigationController pushViewController:listVC animated:YES];
}
-(void)goToFaultList
{
   
    RHFaultAlarmDeviceVC *listVC = [[RHFaultAlarmDeviceVC alloc]init];
    listVC.userId = [PrivateMange share].currentUser.userId;
    listVC.index = 1;
    [self.navigationController pushViewController:listVC animated:YES];
}

#pragma mark --------- 在线设备数量 告警 故障 -----------
-(void)getDeviceOnline
{
    kWeakSelf;
    NSDate *date = [NSDate date];
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:0 minute:0 second:0];
    NSDate *end_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:23 minute:59 second:59];
    
    NSString *begin_time = [NSString stringWithFormat:@"%zd",(NSInteger)[begin_date timeIntervalSince1970]*1000];
    NSString *end_time = [NSString stringWithFormat:@"%zd",(NSInteger)[end_date timeIntervalSince1970]*1000];
    //其他用户
    [RHDeviceOnlineModel startGetWithCompletionAPIKey:H_deviceOnline argument:@{@"beginTime":begin_time,@"endTime":end_time} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        RHDeviceOnlineModel *device = resultModel.data;
        weakSelf.datas[2][CellCount] = [NSString stringWithFormat:@"%ld",(long)device.alarmNumber];
        weakSelf.datas[2][CellCount_1] = [NSString stringWithFormat:@"%ld",(long)device.faultNumber];
        [weakSelf.tableView reloadData];
//        
//        [self.topview setOnlienCount:device.online offlineCount:device.offline];

        self.devStatusDic = request.responseJSONObject[@"data"];
        
        [weakSelf.tableView endHeaderRefresh];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [weakSelf.tableView endHeaderRefresh];
    }];
    
    
    
}
-(void)getPlantAndDevice{
    //终端用户,获取电站和设备数量
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser||[PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser){
        [BaseModel startGetWithCompletionAPIKey:H_getPlantAndDeviceCount argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            self.datas[2][CellCount] = [NSString stringWithFormat:@"%ld",[request.responseObject[@"plant"] integerValue]];
            self.datas[2][CellCount_1] = [NSString stringWithFormat:@"%ld",[request.responseObject[@"device"] integerValue]];
            [self.tableView reloadData];

            [self.tableView endHeaderRefresh];
            } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                [self.tableView endHeaderRefresh];
            }];
    }else{
        //管理端
        [BaseModel startGetWithCompletionAPIKey:H_getUserAndDeviceCount argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            self.datas[1][CellCount] = [NSString stringWithFormat:@"%ld",[request.responseObject[@"user"] integerValue]];
            self.datas[1][CellCount_1] = [NSString stringWithFormat:@"%ld",[request.responseObject[@"device"] integerValue]];
            [self.tableView reloadData];
            [self.tableView endHeaderRefresh];
            
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
            
        }];
    }
}

#pragma mark ---------  获取设备分布 ---
-(void)getDeviceProportion
{
    [RHDeviceTypeModel startGetWithCompletionAPIKey:H_DeviceProportion argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        self.deviceTypeArr = resultModel.data;
        [self.tableView reloadData];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}



#pragma mark ----- 检查二维码信息 ----------
-(void)checkContent:(NSString *)content
{
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error= nil;
    NSDictionary *dicInfo = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (![dicInfo isKindOfClass:[NSDictionary class]]){
        [QMUITips showError:@"数据错误".rh_localized];
        return;
    }
    NSLog(@"---->扫描到的信息:%@",content);
    if([dicInfo[@"userType"] integerValue] >= UserRoleTypeTerminalUser || [dicInfo[@"userType"] integerValue] < UserRoleTypeNationalAgency){
        [QMUITips showError:@"不能绑定此用户".rh_localized];
        return;
    }
    
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_parsingInvitationCodes argument:@{@"invitationCode":dicInfo[@"QRCode"]} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
           
                kWeakSelf;
                QMUIAlertController *alertVC = [QMUIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"%@ %@ ?",@"绑定用户".rh_localized,request.responseJSONObject[@"data"][@"email"]] preferredStyle:QMUIAlertControllerStyleAlert];
                
                [alertVC addAction:[QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                    [QMUITips showLoadingInView:weakSelf.view];
                    [BaseModel startWithCompletionAPIKey:H_bindSuper argument:@{@"sendEmail":request.responseJSONObject[@"data"][@"email"]} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                        if(resultModel.code == 200){
                            
                            [QMUITips showSucceed:@"绑定用户成功".rh_localized inView:self.view hideAfterDelay:1];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                //绑定成功后获取一下个人信息,根据角色重新加载对应控制器
                                [QMUITips showLoadingInView:weakSelf.view];
                                [[PrivateMange share]getUserInfoSuccess:^(RHUserModel * _Nonnull userModel) {
                                    [[NSNotificationCenter defaultCenter]postNotificationName:UserRoleDidChangeNotification object:nil];
                                }];
                            });
                        }
                        
                        
                    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                                
                    }];
                    
                }]];
                [alertVC addAction:[QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleDefault handler:nil]];
                [alertVC showWithAnimated:YES];
           
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
 
   
}


#pragma mark ------ 扫描二维码

- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *content) {
                    [weakSelf checkContent:content];
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"去设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }else{
        NSLog(@"摄像头不可用");
    }

}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"Please allow access photos in iPhone's Settings");
        }else{
            result(NO,@"Please allow access camera in iPhone's Settings");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
